import math
import web

class Gcode:
    
    current_tool = "coffee" # T0

    @staticmethod
    def params_ok(settings, params):
        for param in params:
            if not param.lower() in settings:
                web.debug("settings does not have "+str(param))
                return False
        return True

    @staticmethod
    def make_shake(times, time):
        gcodes = "; Shake \n"
        for time in range(times):
            gcodes += "G1 X2 Y0\n"
            gcodes += "G1 X-2 Y0\n"
        return gcodes

    @staticmethod
    def make_circle(radius, time):
        sections = 20
        r = float(radius)
        t = float(time)
        gcodes = "; Circle radius: "+str(radius)+" time: "+str(time)+"\n"
        for section in range(sections):
            angle = 2*3.14*(float(section)/sections)
            speed = ((2*3.14*r)/t)*60
            gcodes += "G1 X{} Y{} F{}; Angle: {}\n".format(r*math.cos(angle), r*math.sin(angle), speed, angle)
        return gcodes
    
    @staticmethod
    def G0(x, y, z, speed):
        return "G1 X"+str(x)+" Y"+str(y)+" Z"+str(z)+" F"+str(speed)+"\n"

    @staticmethod
    def coarseness(coarseness):
        gcodes =  "M400 ; Wait for steppers to finish\n" 
        gcodes +=  "T1   ; Select Coffee\n"
        gcodes += "G1 X0 Y0 Z0  ;\n"
        if Gcode.current_tool != "coffee":            
            gcodes += "G91          ; Relative coords\n"
            gcodes += "G1 X20 Y10     ; Center on coffee pipe\n"
            gcodes += "G92 X0 Y0 Z0 ; Reset absolute zero\n"
            gcodes += "G90          ; Absolute coords\n"
        gcodes += "G1 E"+str(coarseness)+" F2000 ; Coarseness\n"
        Gcode.current_tool = "coffee"
        return gcodes

    @staticmethod
    def grinder(on):
        gcodes = "M400          ; Wait for steps to finish\n"
        if on:
            return gcodes + "M106 P0 S255        ; Grinder on \n"
        return gcodes + "M106 P0 S0          ; Grinder off\n"

    @staticmethod
    def stop():
        gcodes  = "M84           ; Disable steppers"
        return gcodes

    @staticmethod
    def water(amount):
        gcodes =  "M400 ; Wait for steppers to finish\n" 
        gcodes += "T0       ; Select Water\n"
        if Gcode.current_tool != "water":
            gcodes += "G91      ; Realative coords\n"
            gcodes += "G1 X-20 Y-10 ; Center on water\n"
            gcodes += "G92 X0 Y0 Z0 ; Reset absolute zero\n"
            gcodes += "G90      ; Absolute coords\n"
        gcodes += "G1 E"+str(amount)+" F4000; Open valve\n"
        Gcode.current_tool = "water"
        return gcodes
    
